package radio.learning.nowbutton;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class NowButtonActivity extends Activity
{
    Button              startPlayerBtn;
    Button              pausePlayerBtn;
    Button              restartPlayerBtn;
    private int         playbackPosition = 0;
    static final String AUDIO_PATH       = "/sdcard/Music/HappyNewYear.mp3";
    private MediaPlayer mediaPlayer;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);
        
        startPlayerBtn = (Button) findViewById(R.id.startPlayerBtn);
        pausePlayerBtn = (Button) findViewById(R.id.pausePlayerBtn);
        restartPlayerBtn = (Button) findViewById(R.id.restartPlayerBtn);

        startPlayerBtn.setOnClickListener(new OnClickListener()
        {
            public void onClick(View view)
            {
                try
                {
                    playAudio(AUDIO_PATH);
                    // playLocalAudio();
                    // playLocalAudio_UsingDescriptor();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
        
        pausePlayerBtn.setOnClickListener(new OnClickListener()
        {
            public void onClick(View view)
            {
                if (mediaPlayer != null)
                {
                    playbackPosition = mediaPlayer.getCurrentPosition();
                    mediaPlayer.pause();
                }
            }
        });
        
        restartPlayerBtn.setOnClickListener(new OnClickListener()
        {
            public void onClick(View view)
            {
                if (mediaPlayer != null && !mediaPlayer.isPlaying())
                {
                    mediaPlayer.seekTo(playbackPosition);
                    mediaPlayer.start();
                }
            }
        });
    }

    private void playAudio(String url) throws Exception
    {
        killMediaPlayer();
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource(url);
        mediaPlayer.prepare();
        mediaPlayer.start();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        killMediaPlayer();
    }

    private void killMediaPlayer()
    {
        if (mediaPlayer != null)
        {
            try
            {
                mediaPlayer.release();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
